package com.yhsoft.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhsoft.bill.service.ISysYfzkService;
import com.yhsoft.buyer.entity.BuyerOrder;
import com.yhsoft.buyer.service.IBuyerOrderService;
import com.yhsoft.common.response.PageResult;
import com.yhsoft.common.utils.IDGenerator;
import com.yhsoft.common.vo.Result;
import com.yhsoft.goods.controller.requset.VenderGoodsInVo;
import com.yhsoft.goods.controller.response.AllGoodsOutVo;
import com.yhsoft.goods.entity.CompanyGoods;
import com.yhsoft.goods.entity.GoodsInfo;
import com.yhsoft.goods.service.ICompanyGoodsService;
import com.yhsoft.goods.service.IGoodsInfoService;
import com.yhsoft.sys.controller.Response.AdminAccountOutVo;
import com.yhsoft.sys.controller.Response.CompanyCountOutVo;
import com.yhsoft.sys.controller.Response.CompanySearchOutVo;
import com.yhsoft.sys.controller.Response.DistributorListOutVo;
import com.yhsoft.sys.controller.request.*;
import com.yhsoft.sys.entity.CompanyInfo;
import com.yhsoft.sys.entity.User;
import com.yhsoft.sys.service.ICompanyInfoService;
import com.yhsoft.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: yyyyyyyh
 * @create: 2023-11-13
 * @Version 1.0
 **/
@Api(tags = {"I-线下供应商列管理"})
@RestController
@RequestMapping("/sys/venderInfo")
public class VenderController {
    @Resource
    private ICompanyInfoService companyInfoService;

    @Resource
    private IUserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private ISysYfzkService iSysYfzkService;

    @Resource
    private IGoodsInfoService goodsInfoService;

    @Resource
    private ICompanyGoodsService iCompanyGoodsService;

    @Resource
    private IBuyerOrderService iBuyerOrderService;

    @ApiOperation("供应商管理")
    @GetMapping("/getVenderList")
    public Result<PageResult<DistributorListOutVo>> getVenderList(@RequestParam(value = "distributorName", required = false) String companyName,
                                                                  @RequestParam(value = "phone", required = false) String contactsPhone,
                                                                  @RequestParam(value = "contacts", required = false) String contacts,
                                                                  @RequestParam(value = "pageNo") Long pageNo,
                                                                  @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<CompanyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyInfo::getIsVendor, 1);
        wrapper.eq(StringUtils.hasLength(companyName), CompanyInfo::getCompanyName, companyName);
        wrapper.eq(StringUtils.hasLength(contacts), CompanyInfo::getContacts, contacts);
        wrapper.eq(StringUtils.hasLength(contactsPhone), CompanyInfo::getContactsPhone, contactsPhone);
        wrapper.orderByDesc(CompanyInfo::getId);

        Page<CompanyInfo> page = new Page<>(pageNo, pageSize);
        companyInfoService.page(page, wrapper);
        return Result.success(PageResult.valueOf(page, DistributorListOutVo::valueOf));
    }

    @ApiOperation("数据统计")
    @GetMapping("/getVenderCount")
    public Result<CompanySearchOutVo> getVenderCount() {
        CompanySearchOutVo companySearchOutVo = companyInfoService.search();
        return Result.success(companySearchOutVo);
    }

    @ApiOperation("运营动态")
    @GetMapping("/getCount")
    public Result<CompanyCountOutVo> getCount() {
        CompanyCountOutVo count = companyInfoService.getCountByVender();
        return Result.success(count);
    }

    @ApiOperation("删除供应商")
    @PostMapping("/deleteVender")
    public Result<?> deleteVender(@RequestBody DeleteVenderInVo ids) {
        companyInfoService.deleteDistributor(ids.getVenderId());
        return Result.success("删除成功！");
    }

    @ApiOperation("新增/修改供应商")
    @PostMapping("/setVender")
    public Result<?> setVender(@RequestBody VenderInVo distributorInVo) {
        if (!StringUtils.hasLength(distributorInVo.getCompanyName())) {
            return Result.fail("参数有误！单位名称不能为空！");
        }
        // 不能重复新增
        if (distributorInVo.getId() == null) {
            LambdaQueryWrapper<CompanyInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CompanyInfo::getCompanyName, distributorInVo.getCompanyName());
            List<CompanyInfo> companyInfoList = companyInfoService.list(wrapper);
            if (companyInfoList.size() > 0) {
                return Result.fail("渠道商已经存在，无法新增！");
            }
        }
        companyInfoService.setVender(distributorInVo);

        // 增加应收账款记录
        LambdaQueryWrapper<CompanyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyInfo::getCompanyName, distributorInVo.getCompanyName());
        List<CompanyInfo> companyInfoList = companyInfoService.list(wrapper);
        if (companyInfoList.size() > 0) {
            Integer companyId = companyInfoList.get(0).getId();
            iSysYfzkService.addYszk(companyId);
        }
        return Result.success("成功!");
    }

    @ApiOperation("设置供应商状态（点击即修改）")
    @PostMapping("/setVenderStatus")
    public Result<?> setVenderStatus(@RequestParam(value = "id") Integer id) {
        // 检查该供应商是否有商品属于上架状态，有没有未发货订单
        LambdaQueryWrapper<GoodsInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GoodsInfo::getVendorId, id);
        wrapper.eq(GoodsInfo::getStatusSysUp, 1);
        if(goodsInfoService.getBaseMapper().exists(wrapper)){
            return Result.fail("该供应商有商品没有下架！");
        }else if(iBuyerOrderService.checkVenderOrderStatus(id)){
            return Result.fail("该供应商有商品订单未发货！");
        }
        companyInfoService.setDistributorStatus(id);
        return Result.success("设置成功！");
    }

    @ApiOperation("设置供应商管理员账号")
    @PostMapping("/setVenderAdmin")
    public Result<?> setVenderAdmin(@RequestBody DistributorAdminInVo inVo) {
        // 判断是新增还是修改
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getCompanyId, inVo.getCompanyId())
                .eq(User::getIsAdmin, 1)
                .eq(User::getSysType, "vender");
        User adminUser = userService.getBaseMapper().selectOne(wrapper);
        if (adminUser == null) {
            //不能重复新增
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, inVo.getUsername());
            List<User> users = userService.list(queryWrapper);
            if (users.size() > 0) {
                return Result.fail("电话号码已经存在，无法新增！");
            }
            User user = new User();
            user.setId(IDGenerator.generate16("WebUser"));
            user.setCompanyId(inVo.getCompanyId());
            user.setUsername(inVo.getUsername());
            user.setPassword(passwordEncoder.encode(inVo.getPassword()));
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            user.setIsAdmin(1);
            user.setRole("1");
            user.setDeleted(0);
            user.setSysType("vender");
            userService.addUser(user);
            return Result.success("新增管理员信息成功！");
        } else {
            adminUser.setUsername(inVo.getUsername());
            // 判断密码是否修改
            if (!inVo.getPassword().equals("********")) {
                adminUser.setPassword(passwordEncoder.encode(inVo.getPassword()));
            }
            userService.updateUser(adminUser);
            return Result.success("修改管理员信息成功！");
        }
    }

    @ApiOperation("查询供应商管理员账号")
    @GetMapping("/getVenderAdmin")
    public Result<AdminAccountOutVo> getVenderAdmin(@RequestParam(value = "distributorId") Integer id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getCompanyId, id)
                .eq(User::getIsAdmin, 1)
                .eq(User::getSysType, "vender");
        User adminUser = userService.getBaseMapper().selectOne(wrapper);
        AdminAccountOutVo adminAccountOutVo = new AdminAccountOutVo();
        if (!(adminUser == null)) {
            adminAccountOutVo.setAdminUserId(adminUser.getId());
            adminAccountOutVo.setUsername(adminUser.getUsername());
            adminAccountOutVo.setPassword("********");
        }
        return Result.success(adminAccountOutVo);
    }

    @ApiOperation("供应商商品管理")
    @GetMapping("/getVenderGoods")
    public Result<PageResult<AllGoodsOutVo>> getVenderGoods(VenderGoodsInVo inVo,
                                                            @RequestParam(value = "pageNo") Long pageNo,
                                                            @RequestParam(value = "pageSize") Long pageSize) {
        IPage<AllGoodsOutVo> iPage = goodsInfoService.getVenderGoods(inVo, pageNo, pageSize);
        return Result.success(PageResult.valueOf(iPage));
    }

    @ApiOperation("设置审核状态")
    @PostMapping("/verify")
    public Result<?> verify(@Valid @RequestBody GoodsVerifyInVo inVo) {
        GoodsInfo goodsInfo = goodsInfoService.getById(inVo.getGoodsId());
        if(goodsInfo == null) {
            return Result.fail("获取商品失败！");
        }

        goodsInfo.setStatusVerify(inVo.getStatusVerify());
        goodsInfoService.updateById(goodsInfo);

        return Result.success("设置成功！");
    }

    @ApiOperation("设置上架状态")
    @PostMapping("/setUp")
    public Result<?> setUp(@Valid @RequestBody GoodsUpInVo inVo) {
        GoodsInfo goodsInfo = goodsInfoService.getById(inVo.getGoodsId());
        if(goodsInfo == null) {
            return Result.fail("获取商品失败！");
        }
        if(inVo.getStatusSysUp() == 0){
            // 检查商品是不是在渠道商商城上架
            LambdaQueryWrapper<CompanyGoods> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CompanyGoods::getGoodsId, inVo.getGoodsId());
            wrapper.eq(CompanyGoods::getStatusMallUp, 1);
            if(iCompanyGoodsService.getBaseMapper().exists(wrapper)){
                return Result.fail("当前商品还在渠道商的商品池中,请先下架该商品!");
            }
        }
        goodsInfo.setStatusSysUp(inVo.getStatusSysUp());
        goodsInfoService.updateById(goodsInfo);

        return Result.success("设置成功！");
    }

    @ApiOperation("供应商选择器")
    @GetMapping("/VendorSelector")
    public Result<List<CompanySelectorOutVo>> selector(@RequestParam(value = "vendorName", required = false) String companyName) {
        LambdaQueryWrapper<CompanyInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyInfo::getIsVendor, 1);
        queryWrapper.like(StringUtils.hasLength(companyName), CompanyInfo::getCompanyName, companyName);
        List<CompanyInfo> list = companyInfoService.list(queryWrapper);
        List<CompanySelectorOutVo> outVoList = new ArrayList<>();
        if (list.size() > 0) {
            list.forEach(a -> {
                outVoList.add(new CompanySelectorOutVo(a.getId(), a.getCompanyName()));
            });
        }
        return Result.success(outVoList);
    }

}
